require "import"
import "java.io.FileOutputStream"
import "java.io.OutputStreamWriter"
import "java.io.BufferedReader"
import "java.io.InputStreamReader"
import "java.io.File"
import "java.io.FileInputStream"
import "java.text.SimpleDateFormat"
import "java.util.Date"
import "android.content.ContentValues"
import "android.media.MediaMuxer"
import "android.media.MediaFormat"
import "android.content.*"
import "android.content.pm.PackageManager"

import "android.net.Uri"
import "android.view.View"
import "android.widget.*"
import "android.content.Intent"
import "android.media.MediaPlayer"
import "android.content.Context"
import "android.os.Vibrator"
import "java.lang.reflect.Array"
import "java.lang.System"
import "android.os.Environment"
import "android.media.AudioManager"
import "java.io.File"
import "android.os.Environment"
import "android.widget.ArrayAdapter"
import "android.content.Context"
import "android.os.Vibrator"
import "android.widget.*"
import "com.androlua.*"
 context = activity or service
 vibrator = context.getSystemService(Context.VIBRATOR_SERVICE)
vibrator.vibrate(100)
if isPlaying then
mediaPlayer.stop()
mediaPlayer.reset()
isPlaying = false
currentSoundFilePath = nil
end
--fin de bibliotecas
currentSoundIndex = 0
 folderPath = "/storage/emulated/0/YMusic"
 folder = File(folderPath)
if not folder.exists() then
 success = folder.mkdirs()
if success then
service.asyncSpeak("vui lòng chờ" .. folderPath)
else
service.asyncSpeak("không thể tạo thư mục trong bộ nhớ" .. folderPath)
end
end
 externalPath = Environment.getExternalStorageDirectory().getAbsolutePath()
 soundFolderPath = externalPath .. "/YMusic/"
 soundFolder = File(soundFolderPath)
 soundFiles = soundFolder.listFiles()
 soundFilePaths = {}
if soundFiles ~= nil then
     soundFileCount = Array.getLength(soundFiles)
    if soundFileCount > 0 then
         soundFileCreationTimes = {}
        for i = 0, soundFileCount - 1 do
             soundFile = soundFiles[i]
             soundFilePath = soundFile.getAbsolutePath()
             fileName = soundFile.getName()
             creationTime = soundFile.lastModified()
            table.insert(soundFileCreationTimes, { filePath = soundFilePath, displayName = fileName, creationTime = creationTime })
        end
        table.sort(soundFileCreationTimes, function(a, b)
            return a.creationTime < b.creationTime
        end)
        for i = 1, #soundFileCreationTimes do
             soundFile = soundFileCreationTimes[i]
            table.insert(soundFilePaths, { filePath = soundFile.filePath, displayName = soundFile.displayName })
        end
    else
service.asyncSpeak("thư mục trống! không có tệp âm thanh, vui lòng thêm vào trước khi chạy tiện ích mở rộng này" .. soundFolderPath)        return false
    end
else
    service.asyncSpeak("Không thể truy cập thư mục:" .. soundFolderPath)
    return false
end
function cargarArchivos()
  soundFilePaths = {}
  -- Obtener la lista de archivos en la carpeta
   soundFolderPath = externalPath .. "/YMusic/"
   soundFolder = File(soundFolderPath)
   soundFiles = soundFolder.listFiles()
  if soundFiles ~= nil then
     soundFileCount = Array.getLength(soundFiles)
    if soundFileCount > 0 then
       soundFileCreationTimes = {}
      for i = 0, soundFileCount - 1 do
         soundFile = soundFiles[i]
         soundFilePath = soundFile.getAbsolutePath()
         fileName = soundFile.getName()
         creationTime = soundFile.lastModified()
        table.insert(soundFileCreationTimes, { filePath = soundFilePath, displayName = fileName, creationTime = creationTime })
      end
      table.sort(soundFileCreationTimes, function(a, b)
        return a.creationTime < b.creationTime
      end)
      for i = 1, #soundFileCreationTimes do
         soundFile = soundFileCreationTimes[i]
        table.insert(soundFilePaths, { filePath = soundFile.filePath, displayName = soundFile.displayName })
      end
      list.adapter.clear()
      for i, fileData in ipairs(soundFilePaths) do
        list.adapter.add(fileData.displayName)
      end
      list.adapter.notifyDataSetChanged()
    else
      service.asyncSpeak("Không tìm thấy tệp âm thanh nào trong thư mục:" .. soundFolderPath)
    end
  else
    service.asyncSpeak("Không thể truy cập thư mục:" .. soundFolderPath)
  end
end

 function renameItem(position)
   fileData = soundFilePaths[position + 1]
   file = File(fileData.filePath)
   fileName, fileExtension = string.match(fileData.displayName, "(.-)(%.%w+)$") -- Obtener el nombre y la extensión del archivo
   renameDialog = LuaDialog(context)
  renameDialog.setTitle("Đổi tên tập tin")
   input = EditText(context)
  input.setText(fileName)
  renameDialog.setView(input)
  renameDialog.setPositiveButton("đồng ý", DialogInterface.OnClickListener {
    onClick = function(dialog, which)
       newFileName = tostring(input.getText())
       newFilePath = file.getParent() .. "/" .. newFileName .. fileExtension
       newFile = File(newFilePath)
      if file.renameTo(newFile) then
        fileData.displayName = newFileName .. fileExtension
        adapterItems[position + 1] = fileData -- Actualizar el elemento en adapterItems
        list.adapter.clear()
        for i, fileData in ipairs(soundFilePaths) do
          list.adapter.add(fileData.displayName)
        end
        list.adapter.notifyDataSetChanged()
        service.asyncSpeak("Đã đổi tên tệp thành công.")
        -- dlg.dismiss()
      else
        service.asyncSpeak("đã có lỗi xảy ra khi đổi tên file âm thanh")
      end
      vibrator.vibrate(100)
dialog.dismiss()
    end
  })
  renameDialog.setNegativeButton("hủy", DialogInterface.OnClickListener {
    onClick = function(dialog, which)
      vibrator.vibrate(100)
dialog.dismiss()
    end
  })
  renameDialog.show()
end
 function shareFile(position)
     selectedSoundFilePath = soundFilePaths[position + 1].filePath
    service.shareFile(selectedSoundFilePath)
dlg.dismiss()
end
 function deleteItem(position)
     fileData = soundFilePaths[position + 1]
     file = File(fileData.filePath)
     confirmationDialog = LuaDialog(context)
    confirmationDialog.setTitle("xóa tệp âm thanh")
    confirmationDialog.setMessage("bạn có chắc chắn xóa tệp âm thanh này khỏi danh sách không?")
    confirmationDialog.setPositiveButton("xóa", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            file.delete()
            table.remove(soundFilePaths, position + 1)
            service.asyncSpeak("đã xóa tệp âm thanh khỏi danh sách")
        end
    })
    confirmationDialog.setNegativeButton("hủy", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            vibrator.vibrate(100)
dialog.dismiss()
        end
    })
    confirmationDialog.show()
end
--marcador de dlg
--marcador de dlg
layout = {
    LinearLayout,
    orientation = LinearLayout.VERTICAL,
    {
        TextView,
        text = "máy nghe nhạc",
        textSize = "20sp",
        gravity = "center",
        padding = "16dp",
},
    {
        ListView,
        id = "list",
        layout_width = "fill",
        layout_height = "fill"
    }
}
mediaPlayer = MediaPlayer()
isPlaying = false
currentSoundFilePath = nil
function playSound(soundFilePath)
    if currentSoundFilePath == soundFilePath then
        mediaPlayer.stop()
        mediaPlayer.reset()
        isPlaying = false
        currentSoundFilePath = nil
        return
    end

    if isPlaying then
        mediaPlayer.stop()
        mediaPlayer.reset()
    end
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
    mediaPlayer.setDataSource(soundFilePath)
    mediaPlayer.prepare()
    mediaPlayer.start()
    isPlaying = true
    currentSoundFilePath = soundFilePath
    for i, fileData in ipairs(soundFilePaths) do
        if fileData.filePath == soundFilePath then
            currentSoundIndex = i
            break
        end
    end
    mediaPlayer.setOnCompletionListener(MediaPlayer.OnCompletionListener {
        onCompletion = function(mp)
             nextPosition = currentSoundIndex + 1
            if nextPosition <= #soundFilePaths then
                 nextSoundFilePath = soundFilePaths[nextPosition].filePath
                playSound(nextSoundFilePath)
            end
        end
    })
end
dlg = LuaDialog(service)
dlg.View = loadlayout(layout)
 adapterItems = {}
for i, fileData in ipairs(soundFilePaths) do
    table.insert(adapterItems, fileData.displayName)
end
list.adapter = ArrayAdapter(service, android.R.layout.simple_list_item_1, adapterItems)
dlg.show()
--marcador click simple
list.onItemClick = function(l, v, position, id)
        vibrator.vibrate(100)
         selectedSoundFilePath = soundFilePaths[position + 1].filePath
        playSound(selectedSoundFilePath)
    end
list.onItemLongClick = function(l, v, position, id)
    isLongPress = true
    vibrator.vibrate(100)
if isPlaying then
mediaPlayer.stop()
mediaPlayer.reset()
isPlaying = false
currentSoundFilePath = nil
end
options = {"xoá", "chia sẻ", "đổi tên", "tải lên", "tải xuống"}
     dialog = LuaDialog(context)
    dialog.setTitle("tùy chọn với file âm thanh hiện tại")
     layout = {
        LinearLayout,
        orientation = LinearLayout.VERTICAL,
        {
            Button,
            text = options[1],
            onClick = function(view)
                deleteItem(position)
                vibrator.vibrate(100)
dialog.dismiss()
            end
        },
        {
            Button,
            text = options[2],
            onClick = function(view)
                shareFile(position)
                vibrator.vibrate(100)
dialog.dismiss()
            end
        },
        {
            Button,
            text = options[3],
            onClick = function(view)
                renameItem(position)
                vibrator.vibrate(100)
dialog.dismiss()
            end
        }
    }
     contentView = loadlayout(layout)
    dialog.setView(contentView)
    dialog.setCancelable(true)
    dialog.show()
    return true
end